# coding:utf-8
import datetime
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from web import models


# 将request中的自定义封装到类中，在视图中统一格式调用
class Tracer:
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """如果用户登录，在reuqest中赋值"""
        request.tracer = Tracer()
        user_id = request.session.get('user_id', 0)
        user_obj = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer.user = user_obj  # 名字可以自定义

        # 判断url是否在白名单中
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        if not request.tracer.user:
            return redirect('login')

        # 登录成功访问后台管理时，获取当前用户的额度
        # 1.获取最近的交易记录
        transaction_obj = models.Transaction.objects.filter(user=user_obj, status=2).order_by('-id').first()
        # 2.判断是否过期
        c_time = datetime.datetime.now()
        if transaction_obj.end_datetime and transaction_obj.end_datetime < c_time:
            transaction_obj = models.Transaction.objects.filter(user=user_obj, status=2,
                                                                price_policy__category=1).first()
        request.tracer.price_policy = transaction_obj.price_policy

    def process_view(self, request, view, args, kwargs):

        # 1.判断url是否已manage开头
        if not request.path_info.startswith('/manage/'):
            return
        project_id = kwargs.get('project_id')

        # 2.判断project_id是否为用户创建的
        project_obj = models.Project.objects.filter(id=project_id, creator=request.tracer.user).first()
        if project_obj:
            request.tracer.project = project_obj
            return

        # 3.判断project_id是否为用户参与的
        project_user_obj = models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).first()
        if project_obj:
            request.tracer.project = project_user_obj.project
            return

        return redirect('project_list')
